package ee.sedelitarkvara.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Vector;

public class PortScanner implements Runnable{
	
	/**
	 * Looping port listener.
	 */
	
	private boolean threadDone = false;
	private Logger logger;
	private Settings settings;
	private InputHandler handler;
	Thread t;
	
	public PortScanner(Settings settings, Logger logger){
		this.settings = settings;
		this.logger = logger;
		t = new Thread(this, "pordikuulaja");
	    t.start();
	}
	
	/**
	 * Loop, runs as thread.
	 */
	@Override
	public void run() {
		while(!threadDone){
			try {
				ServerSocket server_socket = new ServerSocket(settings.getPort());
				System.out.println("Server waiting for client on port " + server_socket.getLocalPort());
				logger.log("Server waiting for client on port " + server_socket.getLocalPort());
				Socket socket = server_socket.accept();
				socket.setSoTimeout(settings.getTimeout());
				System.out.println("New connection accepted " +	socket.getInetAddress() + ":" + socket.getPort());
				logger.log("New connection accepted " +	socket.getInetAddress() + ":" + socket.getPort());
				BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8")); 
				try {
					Vector<String> lines = InputHandler.readRequest(input, socket);
					handler = new InputHandler();
					handler.handleVector(lines);
				}catch (Exception e) { 
					//System.out.println(e);
				} 
				// connection closed by client
				try{
					socket.close();
					server_socket.close();
					done();
				}catch(SocketException se){}
			}catch (IOException e) { 
				//System.out.println(e); 
			}
		}
	}
	
	/**
	 * End the loop and garbage collect the thread.
	 */	
	public void done(){
		threadDone = true;
	}
	
	/**
	 * @return - Return InputHandler, which holds book, reader information.
	 */
	public InputHandler getHandler(){
		return handler;
	}
}
